<?php
session_start();
function success(){
    $result = [
        'error'=> 0,
        'message' => '成功'
    ];
    return json_encode($result);
}
function error($msg){
    $data = [
        'error'=> 1,
        'message' => $msg
    ];
    return json_encode($data);
}
if(empty($_POST['username'])){
    die(error('用户名不能为空'));
}
if(empty($_POST['password'])){
    die(error('密码不能为空'));
}
if(empty($_POST['age'])){
    die(error('年龄不能为空'));
}
$username = $_POST['username'];
$password = $_POST['password'];
$age = $_POST['age'];
$sex = $_POST['sex'];
try{
    $db = new PDO('mysql:dbname=qq;host=127.0.0.1','root','123456');
    $statement = $db ->prepare('select * from userinfo where name=:username');
    $statement->execute([':username'=> $username]);
    $user = $statement->fetch();

}catch (PDOException $e){
    echo $e -> getMessage();
}
if($username == $user['name']){
    die(error('用户已存在'));
}else{
    $statement = $db ->prepare('insert into userinfo set name =:username,password =:password,age =:age,sex =:sex');
    $state = $statement->execute([':username'=>$username,':password'=>$password,':age'=>$age,':sex'=>$sex]);
    if($state) {
        echo success();
    }else{
        echo error('用户添加失败！');
    }
}

